package com.efounder.zone.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.UserEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.ChatTextView;
import com.efounder.chat.widget.RoundImageView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.zone.R;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.bean.ZoneMessageBean;
import com.efounder.zone.commentview.ZoneCommentBean;
import com.efounder.zone.util.CommentUtil;
import com.efounder.zone.util.ZoneHelperUtil;
import com.efounder.zone.util.ZoneRequestUtil;
import com.efounder.zone.util.ZoneTimeUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.view.View.GONE;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 空间与我相关
 */
public class ZoneMessageActivity extends BaseActivity {

    private static final String TAG = "ZoneMessageActivity";
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private List<ZoneMessageBean> items = new ArrayList<>();
    private ZoneMessageAdapter adapter;
    private String lastTalksTime = String.valueOf(System.currentTimeMillis());//用于加载更多，传入的时间
    private boolean isRefresh = true;//是否是下拉刷新，第一次加载也算

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mobile_zone_message);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.zone_news);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ZoneMessageAdapter(this, R.layout.mobile_zone_item_message_list, items);
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                getData(lastTalksTime);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                getData(String.valueOf(System.currentTimeMillis()));
            }
        });
        getData(lastTalksTime);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void solveUserEvent(UserEvent userEvent){
        if (userEvent.getEventType()==UserEvent.EVENT_ZONE_RELATE_ME){
            adapter.notifyDataSetChanged();
        }
    }
    private void getData(String lastTime) {
        HashMap<String, String> params = new HashMap<>();
        params.put("time", lastTime);
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        ZoneRequestUtil.getCommonRequest(TAG, "aboutme", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONArray jsonArray = new JSONArray(response);

                    if (isRefresh) {
                        //清空数据
                        items.clear();
                        refreshLayout.finishRefresh();
                    } else {
                        if (jsonArray.length() == 0) {
                            ToastUtils.showShort(R.string.zone_no_more_news);
                        }
                        refreshLayout.finishLoadMore(100);
                    }

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.optJSONObject(i);

                        // 1:点赞， 2:评论， 3.评论回复
                        int aboutType = jsonObject.optInt("aboutType");

                        TalksBean.ObjBean objBean = null;
                        if (jsonObject.optJSONObject("obj") != null) {
                            JSONObject obj = jsonObject.getJSONObject("obj");
                            objBean = new TalksBean.ObjBean();
                            objBean.setId(obj.optInt("id"));
                            objBean.setTransmitStatus(obj.optInt("transmitStatus"));
                            objBean.setTransmitSourceUserid(obj.optInt("transmitSourceUserid"));
                            objBean.setTransmitSourceUsername(obj.optString("transmitSourceUsername"));
                            objBean.setTransmitContent(obj.optString("transmitContent"));
                            objBean.setPostContent(obj.optString("postContent"));
                            objBean.setPostAuthor(obj.optInt("postAuthor"));
                        }


                        TalksBean.CommentBean commentBean = null;
                        if (jsonObject.optJSONObject("comment") != null) {
                            JSONObject comment = jsonObject.getJSONObject("comment");
                            commentBean = new TalksBean.CommentBean();
                            commentBean.setParentId(comment.optInt("parentId"));
                            commentBean.setId(comment.optInt("id"));
                            commentBean.setCommentUserId(comment.optInt("commentUserId"));
                            commentBean.setContent(comment.optString("content"));
                        }

                        ZoneMessageBean zoneMessageBean = new ZoneMessageBean.Builder()
                                .commentBean(commentBean)
                                .objBean(objBean)
                                .aboutType(aboutType)
                                .creatime(jsonObject.optString("creatime"))
                                .userid(jsonObject.optInt("userid"))
                                .objType(jsonObject.optInt("objType"))
                                .build();
                        items.add(zoneMessageBean);
                        //最后一条状态的时间，用于请求更多
                        lastTalksTime = zoneMessageBean.getCreatime();
                    }
                    adapter.notifyDataSetChanged();

                } catch (Exception e) {
                    e.printStackTrace();
                    if (isRefresh) {
                        refreshLayout.finishRefresh(100);
                    } else {
                        refreshLayout.finishLoadMore(100);
                    }
                }
            }

            @Override
            public void onFail(String error) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(100);
                } else {
                    refreshLayout.finishLoadMore(100);
                }
            }
        });
    }


    public class ZoneMessageAdapter extends CommonAdapter<ZoneMessageBean>{

        Context context;

        public ZoneMessageAdapter(Context context, int layoutId, List<ZoneMessageBean> datas) {
            super(context, layoutId, datas);
            this.context = context;
        }

        @Override
        protected void convert(final ViewHolder holder, final ZoneMessageBean zoneMessageBean, int position) {

            RoundImageView mobileZoneAvatar;
            TextView mobileZoneNickname;
            TextView mobileZoneTime;
            TextView tvReply;
            ImageView ivLike;
            ChatTextView mobileZoneContentDescribe;
            ImageView originPostImg;
            TextView originPostUser;
            TextView originPostContent;
            LinearLayout llPostContainer;//原说说内容

            mobileZoneAvatar = holder.getView(R.id.mobile_zone_avatar);
            mobileZoneNickname = holder.getView(R.id.mobile_zone_nickname);
            mobileZoneTime = holder.getView(R.id.mobile_zone_time);
            tvReply = holder.getView(R.id.tv_reply);
            ivLike = holder.getView(R.id.iv_like);
            mobileZoneContentDescribe = holder.getView(R.id.mobile_zone_content_describe);
            originPostImg = holder.getView(R.id.origin_post_img);
            originPostUser = holder.getView(R.id.origin_post_user);
            originPostContent = holder.getView(R.id.origin_post_content);
            llPostContainer = holder.getView(R.id.ll_post_container);


            User user = WeChatDBManager.getInstance().getOneUserById(items.get(position).getUserid(),UserEvent.EVENT_ZONE_RELATE_ME);
            LXGlideImageLoader.getInstance().showUserAvatar(context, mobileZoneAvatar, user.getAvatar());
            mobileZoneNickname.setText(user.getNickName());
            mobileZoneAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ZoneHelperUtil.gotoOtherZone(context, items.get(holder.getAdapterPosition()).getUserid());
                }
            });
            mobileZoneNickname.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ZoneHelperUtil.gotoOtherZone(context, items.get(holder.getAdapterPosition()).getUserid());
                }
            });
            llPostContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, MobileZoneDetailActivity.class);
                    intent.putExtra("id", items.get(holder.getAdapterPosition()).getObjBean().getId());
                    context.startActivity(intent);
                }
            });
            tvReply.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ZoneCommentBean zoneCommentBean = new ZoneCommentBean();
                    zoneCommentBean.setParentId(zoneMessageBean.getCommentBean().getParentId());
                    zoneCommentBean.setId(zoneMessageBean.getCommentBean().getId());
                    zoneCommentBean.setCommentUserId(zoneMessageBean.getCommentBean().getCommentUserId());
                    TalksBean talksBean = new TalksBean();
                    talksBean.setObjType(zoneMessageBean.getObjType());
                    talksBean.setObj(zoneMessageBean.getObjBean());
                    CommentUtil.sendComment(context, 0, zoneCommentBean, talksBean, getSupportFragmentManager());
                }
            });
            mobileZoneTime.setText(ZoneTimeUtil.formatTime(items.get(position).getCreatime()));
            int aboutType = items.get(position).getAboutType();
            // 1:点赞， 2:评论， 3.评论回复
            if (aboutType == 1) {
                ivLike.setVisibility(View.VISIBLE);
                mobileZoneContentDescribe.setText(R.string.zone_zan_me);
                tvReply.setVisibility(GONE);

            } else if (aboutType == 2 || aboutType == 3) {
                tvReply.setVisibility(View.VISIBLE);
                ivLike.setVisibility(GONE);
                mobileZoneContentDescribe.setText("");
                //判断content中是否为json数据结构
                try {
                    JSONObject jsonObject = new JSONObject(items.get(position).getCommentBean().getContent());

                    if (jsonObject.has("text")) {
                        String commentText = jsonObject.getString("text");

                        mobileZoneContentDescribe.setText(commentText);
                    }
                    if (jsonObject.has("images")) {
                        JSONArray jsonArray = jsonObject.getJSONArray("images");
                        ArrayList<String> imgList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            imgList.add(jsonArray.getString(i));
                        }
//                        if (imgList.size() <= 0) {
//                            holder.bplCommentDetailPhoto.setVisibility(View.GONE);
//                        } else {
//                            holder.bplCommentDetailPhoto.setVisibility(View.VISIBLE);
//                            holder.bplCommentDetailPhoto.setData(imgList);
//                            holder.bplCommentDetailPhoto.setDelegate(CommentListAdapter.this);
//                        }
                    }

                } catch (Exception e) {
//                    holder.bplCommentDetailPhoto.setVisibility(View.GONE);
//                    String commentText = content;
//                    setCommentText(zoneCommentBean, holder.tvCommentDetail, commentText);
                }
            } else if (aboutType == 4) {
                tvReply.setVisibility(GONE);
                ivLike.setVisibility(GONE);
                mobileZoneContentDescribe.setText(R.string.zone_forward_my_ss);
            }
            if (items.get(position).getObjBean() == null || !items.get(position).getObjBean().getPostContent().contains("text")) {
                originPostImg.setVisibility(GONE);
                originPostUser.setVisibility(GONE);
                originPostContent.setText(R.string.zone_ss_is_delete);
                llPostContainer.setClickable(false);
                tvReply.setVisibility(GONE);
            } else {
                llPostContainer.setClickable(true);
                originPostImg.setVisibility(GONE);
                try {
                    JSONObject postContent = new JSONObject(items.get(position).getObjBean().getPostContent());
                    String text = postContent.optString("text");
                    if (null != text) {
                        originPostContent.setText(text);
                    }
                    User user1 = WeChatDBManager.getInstance().getOneUserById(items.get(position).getObjBean().getPostAuthor());
                    originPostUser.setVisibility(View.VISIBLE);
                    originPostUser.setText(user1.getNickName() + ":");
                    int type = postContent.optInt("type");
                    if (type == 2) {
                        JSONArray imgArray = postContent.optJSONArray("images");
                        if (imgArray.length() > 0) {
                            originPostImg.setVisibility(View.VISIBLE);
                            LXGlideImageLoader.getInstance().displayImage(context, originPostImg, imgArray.getString(0));
                        }else {
                            originPostImg.setVisibility(GONE);
                        }

                    }
                    //todo 根据类型显示
                } catch (Exception e) {
                    e.printStackTrace();
                    llPostContainer.setClickable(true);
                    originPostImg.setVisibility(GONE);
                    originPostUser.setVisibility(GONE);
                    originPostContent.setText(R.string.zone_ss_is_delete);
                    tvReply.setVisibility(GONE);
                }
            }
        }
    }
}
